import axios from "axios";
import { ElMessage } from 'element-plus'
import router from "../router/router";
import store from "../store/store";

import JSONbig  from  'json-bigint';

const JsonBigToString = JSONbig({ storeAsString: true })

/* 与后端集成测试时 打开*/
axios.defaults.baseURL = store.getters.getRequestUrl
const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    },
    transformResponse: [function (data) {
        try {
            //转换
            return JsonBigToString.parse(data);
        } catch (err) {
            //转换失败就直接按原数据返回
            return data;

        }
    }]
})


// 前置拦截
request.interceptors.request.use(config => {
    config.headers['Authorization'] = store.getters.getToken;
    // console.log(localStorage.getItem("token"))
    return config;
})

//后置拦截
request.interceptors.response.use(response =>{
    // console.log(response.data.code)
        if(response.data.code === 200){
            return response;
        }else{
            // ElMessage.error(response.data.msg);
            return Promise.reject(response.data.msg);
        }
    },
    error => {
        // console.log(error.message)
        // ElMessage.error("请求出错，请检查后台")
        // return Promise.reject(error);

        // if(error.response.data){
        //     error.message = error.response.data.msg;
        // }
        if(error.response.status === 401 ||error.response.status === 403){
            store.commit('REMOVE_INFO');
            router.push("/login").then();
        }
        ElMessage.error(error);
        return Promise.reject(error);
    }

)

export default request;
